package com.tea.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tea.Model.Dynamic;
import com.tea.service.DynamicService;
import com.tea.utils.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/dnamic")
public class DynamicController {

    @Resource
    private DynamicService dynamicService;

    // 分页查询动态列表
    @GetMapping("/list")
    public Result<IPage<Dynamic>> list(@RequestParam(defaultValue = "1") Integer page,
                                       @RequestParam(defaultValue = "10") Integer size,
                                       @RequestParam(required = false) Long typeId) {
        // 创建 QueryWrapper 并指定降序排序
        QueryWrapper<Dynamic> queryWrapper = new QueryWrapper<>();
        
        // 如果指定了动态类型，则按类型筛选
        if (typeId != null) {
            queryWrapper.eq("type_id", typeId);
        }
        
        queryWrapper.orderByDesc("create_time"); // 按 create_time 降序排列
        // 将 QueryWrapper 传入 page 方法
        return Result.success(dynamicService.page(new Page<>(page, size), queryWrapper));
    }

    // 发布动态
    @PostMapping
    public Result<Boolean> saveDynamic(@RequestBody Dynamic dynamic) {
        dynamic.setId(System.currentTimeMillis());
        dynamic.setCreateTime(LocalDateTime.now());
        return Result.success(dynamicService.save(dynamic));
    }

    // 删除动态
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteDynamic(@PathVariable Long id) {
        return Result.success(dynamicService.removeById(id));
    }

    // 修改动态
    @PutMapping("/{id}")
    public Result<Boolean> updateDynamic(@RequestBody Dynamic dynamic) {
        return Result.success(dynamicService.updateById(dynamic));
    }

    // 动态详情
    @GetMapping("/{id}")
    public Result<Dynamic> detail(@PathVariable Long id) {
        return Result.success(dynamicService.getById(id));
    }

    // 获取首页公告（最新3条）
    @GetMapping("/announcements")
    public Result<IPage<Dynamic>> getAnnouncements() {
        QueryWrapper<Dynamic> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        
        // 只获取最新的3条公告
        return Result.success(dynamicService.page(new Page<>(1, 3), queryWrapper));
    }
}

